/**
 * @file microwave_module.c
 * @author Rocky
 * @brief 微波模块驱动程序
 * @version 0.1
 * @date 2024-03-26
 * 
 * @copyright Copyright (c) 2024
 * 
 */

#include "spidev_interface.h"
#include "gpio_ctrl.h"

#define PROGRAM_NAME "microwave_interface"

/* 模块电源 高电平开启、
   复位 低电平有效
   接收开启 高电平有效 */
#define WAV_PWR_PORT "gpiochip6"
#define WAV_PWR_PIN  15
#define WAV_RST_PORT "gpiochip9"
#define WAV_RST_PIN  6
#define WAV_DIS_PORT "gpiochip9"
#define WAV_DIS_PIN  7
#define ENABLE       1
#define DISABLE      0

static int microwave_spi_fd;
static uint32_t microwave_spi_mode = SPI_MODE_0;
static int8_t microwave_spi_bits = 8;
static uint32_t microwave_spi_speed = 500000;

/**
 * @brief 微波模块初始化
 * 
 * @return int 
 */
int microwave_module_init()
{
    // 微波模块的SPI设备是：/dev/spidev1.0
    microwave_spi_fd = init_spi("/dev/spidev1.0");
    set_spi_mode(microwave_spi_fd, microwave_spi_mode, microwave_spi_bits, microwave_spi_speed);

    // 1. 复位失能 2. 接收开启 3. 打开电源
    gpio_set_value(WAV_RST_PORT, WAV_RST_PIN, ENABLE);
    gpio_set_value(WAV_DIS_PORT, WAV_DIS_PIN, ENABLE);
    gpio_set_value(WAV_PWR_PORT, WAV_PWR_PIN, ENABLE);
    return microwave_spi_fd;
}

int close_microwave_module()
{
    int ret;
    ret = close_spi(microwave_spi_fd);

    // 为测试方便不关闭电源，后续根据需要增加关闭电源的函数
    // gpio_set_value(WAV_PWR_PORT, WAV_PWR_PIN, DISABLE);
    return ret;
}

void microwave_module_power_off()
{
    gpio_set_value(WAV_PWR_PORT, WAV_PWR_PIN, DISABLE);
}

/**
 * @brief 设置微波发送模块的频率码和衰减
 * 
 * @param MHz 频率，范围800MHz~2000MHz
 * @param attenuation 衰减控制，0-30dB
 * @return int 
 */
void set_microwave_tx_frequency(uint32_t kHz, uint8_t attenuation)
{
    uint8_t tx[4];
    uint8_t rx[4];
    uint8_t freq_code;

    if (kHz < 800000)
        kHz = 800000;
    if (kHz > 2000000)
        kHz = 2000000;
        
    // 发射模块的频率协议有偏移
    kHz += 80000;

    if (attenuation > 30)
        attenuation = 30;

    freq_code = (kHz - 800000) / 10000 + 0x01;

    tx[0] = 0x01;
    tx[1] = freq_code;
    tx[2] = attenuation;

    transfer(microwave_spi_fd, tx, rx, sizeof(tx));
}


/**
 * @brief 设置微波接收模块的频率码和衰减
 * 
 * @param MHz 频率，范围800MHz~2000MHz
 * @param attenuation 衰减控制，0-30dB
 * @return int 
 */
void set_microwave_rx_frequency(uint32_t kHz, uint8_t attenuation)
{
    uint8_t tx[4];
    uint8_t rx[4];
    uint8_t freq_code;

    if (kHz < 800000)
        kHz = 800000;
    if (kHz > 2000000)
        kHz = 2000000;
    if (attenuation > 30)
        attenuation = 30;

    freq_code = (kHz - 800000) / 10000 + 0x01;

    tx[0] = 0x01;
    tx[1] = freq_code;
    tx[2] = attenuation;

    transfer(microwave_spi_fd, tx, rx, sizeof(tx));
}

void get_microwave_module_status(uint8_t *rx)
{
    uint8_t tx[4];
    tx[0] = 0x02;
    tx[1] = 0;
    tx[2] = 0;
    tx[3] = 0;
    transfer(microwave_spi_fd, tx, rx, sizeof(tx));
}
